package breakthrough.AlphaBetaPlayer;
import breakthrough.BreakthroughMove;
import breakthrough.BreakthroughState;

import game.*;

/**
	Amazing Alpha beta player of breakthrough

	@author: Andrew Oberlin, John Malloy, Lamont Walker
**/
public class LamontsSexyBreakthroughPlayer2012v1 extends GamePlayer {
	private Timer timer;
	private int numOurMoves;
	
	/**
	 * Constructor for our GamePlayer
	 * 
	 * @param n nickname string
	 */
	public LamontsSexyBreakthroughPlayer2012v1(String n) {
		super(n, new BreakthroughState(), false);
	}
	
	/**
	 * Retrieves the move for the given state when it is our turn
	 * 
	 * @param state The GameState for this turn
	 * @param lastMove The previous move which can be parsed
	 */
	public GameMove getMove(GameState state, String lastMove) {		
		BreakthroughState board = (BreakthroughState) state;
		BreakthroughMove trial = this.hasWinningState(board);
		Opening opening = new Opening(board, this.numOurMoves);
		if (trial != null) {
			return trial;
		}
		else if (opening.isOpeningTime()){
			BreakthroughMove move = opening.openingMove();
			this.numOurMoves++;
			return move;
		}
		return new IterativeDeepeningAlphaBeta(this.timer, board.getNumMoves()).search(board);
	}
	
	private BreakthroughMove hasWinningState(BreakthroughState board) {
		char ours = board.who == GameState.Who.HOME ? BreakthroughState.homeSym : BreakthroughState.awaySym;
		int row = board.who == GameState.Who.HOME ? BreakthroughState.N - 2 : 1;
		int dir = board.who == GameState.Who.HOME ? 1 : -1;
		for (int col = 0; col < BreakthroughState.N; col++) {
			if (board.board[row][col] == ours) {
				if (col > 0) {
					return new BreakthroughMove(row, col, row + dir, col - 1);
				}
				else {
					return new BreakthroughMove(row, col, row + dir, col + 1);
				}
			}
		}
		
		return null;
	}
	
	public void startGame(String opponent) {
		this.numOurMoves = 0;
		this.timer = new Timer(420);
	}
	
	public void timeOfLastMove(double secs){ 
		this.timer.update(secs);
	}
	
	public static void main(String [] args)	{
		GamePlayer p = new LamontsSexyBreakthroughPlayer2012v1("LamontsSexyBreakthroughPlayer2012v1");
		p.compete(args);
	}
}
